// core/pointsService.js
const { updateUserPoints, addPointsHistory, fetchUserPointById} = require('./databaseService');
const { getTaskPointsMapping } = require('../utils/mappings');

function getRequiredPoints(taskData) {
  let defaultPoints = 1;

  if (taskData.requiredPoints) return taskData.requiredPoints;

  let points = getTaskPointsMapping(taskData.taskType) || defaultPoints;

  const timeStr = taskData?.times;
  if (timeStr) {
    const match = timeStr.match(/(\d+)/);
    if (match) {
      const seconds = parseInt(match[1], 10);
      if (seconds > 46) {
        points += 1;
      }
    }
  }
  return points;
}

/**
 * 扣除用户积分并记录消费
 */
async function consumePoints(userId, requiredPoints, taskType, taskId) {
  await updateUserPoints(userId, -requiredPoints);
  await addPointsHistory(
    userId,
    -requiredPoints,
    'consume',
    `提交${taskType}任务`,
    taskId
  );
}

/**
 * 查询用户积分，并返回是否支持任务提交
 */
async function checkUserPoints(userId, task){
  const requiredPoints = getRequiredPoints(task);
  const userResult = await fetchUserPointById(userId);

  if (!userResult) {
    return {
      success: false,
      code: 404,
      message: '用户不存在',
      userId: userId,
    };
  }

  const currentPoints = userResult.points || 0;

  // 校验积分
  if (currentPoints < requiredPoints) {
    return {
      success: false,
      code: 403,
      message: `积分不足，需要 ${requiredPoints} 积分，当前有 ${currentPoints} 积分`,
      points: currentPoints
    };
  }

  // 积分足够
  return {
    success: true,
    points: currentPoints
  };

}


module.exports = {
  getRequiredPoints,
  consumePoints,
  checkUserPoints
};
